﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net.Sockets;
using System.IO;
using System.Net;
using System.Threading;
using Utility;

namespace _411Client.Connect
{
    class FileSend
    {
        /// <summary>
        /// 
        /// </summary>
        public int Port { get; set; }
        private readonly Thread _thread;
        private Socket _s;
        private readonly String _path;
        private Socket _serverSocket;

        /// <summary>
        /// 
        /// </summary>
        /// <param name="t"></param>
        /// <param name="path"></param>
        public FileSend(Thread t,String path)
        {
            _thread = t;
            _path = path;
        }
        
        /// <summary>
        /// 
        /// </summary>
        public void Run()
        {
            Port = GetPort(); // 绑定端口,返回端口
            
            //提供一个 IP 地址，指示服务器应侦听所有网络接口上的客户端活动
            IPAddress ip = IPAddress.Any;
            IPEndPoint serverInfo = new IPEndPoint(ip, Port);
            _serverSocket.Bind(serverInfo);//将SOCKET接口和IP端口绑定
            _serverSocket.Listen(10);//开始监听，并且挂起数为10
            _s = _serverSocket.Accept();
            byte [] recvBytes = new byte[1024];
            _s.Receive(recvBytes);
            String type = Encoding.Unicode.GetString(recvBytes);
            if(type.Equals(MessageType.MESSAGE_OK))
            {
                SendFile(_path);
            }
            else
            {
                _serverSocket.Close();
                _thread.Abort();
            }
        }

        //发送文件
        public void SendFile(String path)
        {
            NetworkStream nStrm = new NetworkStream(_s);//获取流

            //以二进制格式读取文件内容
            FileStream fsr = new FileStream(path, FileMode.Open);
            byte[] buffer = new byte[10240];
            int num=fsr.Read(buffer, 0, buffer.Length);
            while(num!=-1)
            {
                //以二进制格式发送文件内容
                nStrm.Write(buffer, 0, buffer.Length);
                nStrm.Flush();
                buffer = new byte[10240];
                num = fsr.Read(buffer, 0, buffer.Length);
            }
            
            fsr.Close();
            nStrm.Close();
            _s.Close();
            _serverSocket.Close();
        }

        //获得可用端口
        public int GetPort()
        {
            int i = 10000;
            while (true)
            {
                try
                {
                    _serverSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                    break;
                }
                catch 
                {
                    i++;
                }
            }
            return i;
        }
    }
}
